package service

import (
	"anban/models"
	"anban/utils"
	"fmt"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

// 获取卡号信息
func GetCardNumLibInfo(p map[string]interface{}) *models.CardNumLib {
	o := orm.NewOrm()
	cardNumLib := &models.CardNumLib{}
	qs := o.QueryTable("CardNumLib")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["num"]; ok {
		qs = qs.Filter("num", p["num"])
	}
	qs.OrderBy("-id").One(cardNumLib)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		cardNumLib.CreatedShow = cardNumLib.Created.Format("2006-01-02 15:04:05")
	}
	return cardNumLib
}


// 生成卡号
func AddCardNums(input url.Values) (int64, error) {
	o := orm.NewOrm()
	var maxCardNum int64
	var cardNums []models.CardNumLib

	school := &models.School{}
	if _, ok := input["school_id"]; ok {
		school.Id = utils.Atoi64(input["school_id"][0])
		o.Read(school)
	}

	p := map[string]interface{}{}
	cardNumLib := GetCardNumLibInfo(p)
	if cardNumLib.Id > 0 {
		maxCardNum = utils.Atoi64(cardNumLib.Num)
	}

	count, _ := strconv.Atoi(input["count"][0])
	for i := 0; i < count; i++ {
		maxCardNum++
		cardNumLib := models.CardNumLib{}
		cardNumLib.School = school
		cardNumLib.Num = fmt.Sprintf("%010d", maxCardNum)
		cardNums = append(cardNums, cardNumLib)
	}

	return o.InsertMulti(1, cardNums)
}

// 获取文章列表
func GetCardNumLibList(p map[string]interface{}) (int64, []*models.CardNumLib) {
	var cardNumLibList []*models.CardNumLib
	o := orm.NewOrm()
	qs := o.QueryTable("CardNumLib")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["schoolId"]; ok {
		qs = qs.Filter("school_id", p["schoolId"])
	}
	if _, ok := p["schoolName"]; ok {
		qs = qs.Filter("School__Name__contains", p["schoolName"])
	}
	if _, ok := p["cardNum"]; ok {
		qs = qs.Filter("num__contains", p["cardNum"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&cardNumLibList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, cardNumLib := range cardNumLibList {
			cardNumLib.CreatedShow = cardNumLib.Created.Format("2006-01-02 15:04:05")
		}
	}
	return totalCount, cardNumLibList
}